﻿using System.Collections.Generic;
using Gp.Scripts.Core;
using Gp.Scripts.Equip;
using Gp.Scripts.Utils;
using Michsky.UI.Heat;
using QFramework;
using UnityEngine;

namespace Gp.Scripts.GUI {
    public class EquipSlotRangedPart : BaseWeaponSlotPart, IController {
        private RangedWeaponInfo _reference;
        [SerializeField] private Transform bulletDisplayParent;
        // [SerializeField] private TMP_Text ammoText;
        [SerializeField] private BulletDisplayIcon bulletIconPrefab;
        [SerializeField] private SwitchManager shootModeSwitch;
        
        
        private List<BulletDisplayIcon> _bulletIcons;

        private const int MaxBulletCnt = 25;
        
        private void Start() {
            // this.RegisterEvent<WeaponAmmoChangeEvent>(args => {
                // if (_reference == null || args.Entity.Info != _reference) return;
                // Show(_reference);
            // }).UnRegisterWhenGameObjectDestroyed(gameObject);


            shootModeSwitch.onValueChanged.AddListener(OnSwitchChange);
            
            
            _bulletIcons = new List<BulletDisplayIcon>();

            for (int i = 0; i < MaxBulletCnt; i++) {
                var obj = Instantiate(bulletIconPrefab, bulletDisplayParent, true);
                _bulletIcons.Add(obj);
                obj.Clear();
            }
        }




        public void Show(RangedWeaponInfo info) {
            _reference = info;
            gameObject.SetActive(true);

            shootModeSwitch.gameObject.SetActive(info.CanDcShoot);
            if (_reference.CanDcShoot) shootModeSwitch.isOn = _reference.DcShoot;


            int shootSpeed = info.ShootSpeed;
            
            
            // 向上取整
            int fragmentCount = MathUtil.Ceil(info.maxAmmo, shootSpeed);
            int empty = fragmentCount - MathUtil.Ceil(info.AmmoRemain, shootSpeed);
            
            

            
            for (int i = 0; i < _bulletIcons.Count; i++) {
                var obj = _bulletIcons[i];
                if (i >= fragmentCount) {
                    obj.Clear();
                    continue;
                }


                obj.Show();
                if (i < empty) {
                    obj.MarkAsEmpty();
                } else if (i == empty) {
                    obj.MarkAsCur();
                } else {
                    obj.MarkAsRemain();
                }
            }
        }
        


        public override void Hide() {
            _reference = null;
            gameObject.SetActive(false);
        }


        
        private void OnSwitchChange(bool isOn) {
            if (_reference is not {CanDcShoot: true}) return;
            _reference.SetShootMode(isOn);
            Show(_reference);
            Global.Get<BattleSystem>().ToLastState();
        }





        public IArchitecture GetArchitecture() {
            return MainArchitecture.Interface;
        }
    }
}